import moment from 'moment';
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import * as service from '../pages/customer/information/components/EligibilityList/service/customerViewService';

/* eslint-disable */
export default {
  namespace: 'customerView',
  state: {
    // 客户明细信息
    customerInfo: {},
    contacts: [],
    gamePref: [],
    terminalInfos: [],
    preExpiyDate: '',
    isFavorite: '',
    // 客户标签
    labelInfo: [],
    labelActivity: [],
    // 会员卡信息
    memberInfo: [],
    detailInfos: [],
    // 客户联系人列表
    associatesList: [],
    // 客户偏好信息
    preferenceInfo: [],
    // 客户酒店概要
    hotelBookingSummarize: {},
    // 客户vouchers信息
    vouchers: [],
    // 客户grInfo
    grInfo: {},
    // 客户inviteInfo
    inviteInfo: {},
    // 客户voucherTrans
    voucherTrans: [],
    // 客户hotelTrans
    hotelTrans: [],
    localHotelTrans: [],
    authorities: [],
    //allTransactions
    allTransactions: [],
    currentHotelTrans: [],
    currentVoucherTrans: [],
    resultCode: 0,
    voucherTransErrorFlag: false,
    hotelTransErrorFlag: false,
    //allTransactions加载状态
    transactionsStatus: true,
    //客户统计信息
    statisticsDetailList: [],
    //当前酒店入住信息
    hotelInfo: [],
    //查询景点通行证
    attractionPassInfos: [],
    //配置属性
    attributeList: [],
    //客户实例化属性
    customerAttributeList: [],
    /*    showIconName:[],
    showIcon: [],*/
    //客户资料历史轨迹查询
    historyList: [],
    userRegionWithRmCodeList: [],
    historyTotalSize: 0,
    historyLoading: false,
    //客户偏好信息
    customerPreferenceInfoList: [],
    preferenceConfigList: [],
    preferenceConfigLoading: false,
    // 客户other casiono 实例化数据
    customerOtherCasinoList: [],
    // 客户other casiono 实例化数据留底
    customerOtherCasinoConfirmList: [],
    // other casinno config 数据
    customerOtherCasinoConfigList: [],
    editFlag: false,
    userAccessList: [],
    //hotellog
    hotelLogInfos: [],
    //客户outstanding列表
    outstandingList: [],
    outstandingLoading: false,
    outstandingCurrent: 1,
    outstandingPageSize: 5,
    outstandingTotal: 0,
    //outstandingDetail信息
    detailOutstandingInfo: {},
    outstandingDetailVisible: false,
    consideration:[],
    eventSessionList:[],
    //配置信息
    activityTypeList: [],
    statusList: [],
    //eligibilityList信息
    eligibilityList: [],
    compBalance: '',
    //日志中用户的信息
    logsUserMessage: [],
    campaignTypeList: [],
    nboInfoList: [],
    taskTabActiveKey:'1',
    activityManualStatusList:[],
    activityManualTypeList:[],
    activityManualSubTypeList:[],
    subTypeList:[],
    manualActivityTotal:0,
    manualActivityCurrent:1,
    manualActivityPageSize: 5,
    manualActivityList:[],
    userGroupingList: [],
    createAccess: false,
    createAccessMenu: false,
    menuData: [],
    cancelVisible:false,
    cancelActivityId:'',
    // contactHistory
    contactDropDownList:{},
    contactHistory:'',
    reasonHistorys:[],
    inboundCallData:[],
    feedBackContactReasonData:'',
    searchValue: {},
  },
  subscriptions: {
    setup({ dispatch }) {},
  },
  effects: {
    *fetchCustomerDetail({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          customerDetailLoadingFlag: true,
        },
      });
      const D = yield call(service.getProfileDetail, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          customerDetailLoadingFlag: false,
        },
      });
      const {
        data: { result },
      } = D;
      yield put({
        type: 'customerDetailSave',
        payload: result,
      });
    },
    *fetchCustomerPhoto({ payload }, { call, put, select }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({ type: 'spinLoading/setLoadingFlag', payload: { customerDetailPhotoLoadingFlag: true, }});
      const D = yield call(service.getCustomerPhoto, { ...payload });
      yield put({ type: 'spinLoading/setLoadingFlag', payload: { customerDetailPhotoLoadingFlag: false, }});
      const { data: { result }, } = D;
      const customerInfo = yield select(state => state.customerView.customerInfo);
      customerInfo.customerPhoto = result.customerPhoto;
      //console.log('fetchCustomerPhoto customerInfo : ', customerInfo);
      yield put({ type: 'save',payload:{customerInfo} });
      //customerPhoto
    },
    *fetchCustomerMember({ payload }, { call, put, select }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({ type: 'spinLoading/setLoadingFlag', payload: { customerDetailMemberLoadingFlag: true, }});
      const D = yield call(service.getCustomerMember, { ...payload });
      yield put({ type: 'spinLoading/setLoadingFlag', payload: { customerDetailMemberLoadingFlag: false, }});
      const { data: { result }, } = D;
      const customerInfo = yield select(state => state.customerView.customerInfo);
      customerInfo.residentialStatus = result.residentialStatus;
      customerInfo.customerTypes = result.customerTypes;
      // console.log('fetchCustomerMember customerInfo : ', customerInfo);
      yield put({ type: 'save',payload:{customerInfo} });
      // residentialStatus
      // customerTypes
    },
    *fetchCustomerGame({ payload }, { call, put, select }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({ type: 'spinLoading/setLoadingFlag', payload: { customerDetailGameLoadingFlag: true, }});
      const D = yield call(service.getCustomerGame, { ...payload });
      yield put({ type: 'spinLoading/setLoadingFlag', payload: { customerDetailGameLoadingFlag: false, }});
      const { data: { result }, } = D;
      const customerInfo = yield select(state => state.customerView.customerInfo);
      customerInfo.terminalInfos = result.terminalInfos;
      yield put({ type: 'save',payload:{customerInfo} });
      yield put({ type: 'save',payload:{terminalInfos: result.terminalInfos} });
      // console.log('fetchCustomerGame result : ', result);
      // terminalInfos
    },
    *fetchLabelList({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: true,
        },
      });
      const {
        data: {
          resultCode,
          result: { labelGroups = [] },
        },
      } = yield call(service.getLabelList, payload);
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: false,
        },
      });
      if (resultCode === '0') {
        const labelInfo = [];
        const labelActivity = [];
        labelGroups.map(e => {
          const { isVisible = 'N', groupName, order, } = e;
          if (isVisible === 'Y') {
            labelInfo.push(e);
            labelActivity.push(order);
          }
          return e;
        });
        yield put({
          type: 'labelListlSave',
          payload: {
            labelInfo,
            labelActivity,
          },
        });
      } else {
        yield put({
          type: 'labelListlSave',
          payload: {},
        });
      }
    },
    *fetchEligibilityList({ payload }, { call, put }) {
      const { data: { resultCode, resultMsg, result: { eligibilityList } = '' } = '' } = yield call(
        service.getEligibilityList,
        { ...payload }
      );
      if (!resultCode || resultCode !== '0') return;
      yield put({
        type: 'eligibilityListSave',
        payload: eligibilityList,
      });
    },
    *fetchGetCampaignTypeList({ payload }, { call, put }) {
      //yield put({ type: 'global/refreshSessionTime' });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getCampaignAttrConfig, { ...payload });
      if (resultCode !== 0 || !result) {
        return;
      }
      yield put({
        type: 'campaignTypeSave',
        payload: result,
      });
    },
    *getContactHistory({ payload }, { call, put,select }) {
      const {callFlag = false}=payload;
      let contactHistoryParam = payload;
      if (callFlag){
        const {searchValue={}} = yield select(state => state.customerView);
        contactHistoryParam = searchValue;
      }
      const {
        data: { result='',resultCode='', },
      } = yield call(service.getContactHistory,contactHistoryParam) || '';
      if(resultCode!=0)return;
      yield put({ type: 'save',payload:{contactHistory:result} });
    },
    *getContactDropDownList({ payload }, { call, put,select }) {
      const {type}=payload;
      const {
        data: { result:{contactDropDowns=[]}='',resultCode='', },
      } = yield call(service.getContactDropDownList,type) || '';
      if(!resultCode || resultCode!=='0')return;
      let {contactDropDownList={}} = yield select(state => state.customerView);
      contactDropDownList = {...contactDropDownList,contactReason:contactDropDowns};

      yield put({ type: 'save',payload:{contactDropDownList} });
    },
    *getContactDics({ payload }, { call, put,select }) {
      const {type}=payload;
      const {
        data: { resultObj=[],success=false, },
      } = yield call(service.getContactDics,type) || '';
      if(!success)return;
      let {contactDropDownList={}} = yield select(state => state.customerView);
      if(type==='1'){
        contactDropDownList = {...contactDropDownList,channel:resultObj};
      }
      if(type==='2'){
        contactDropDownList = {...contactDropDownList,contactType:resultObj};
      }
      yield put({ type: 'save',payload:{contactDropDownList} });
    },
    *modifyContactHistory({ payload }, { call, put }) {
      const {
        data: { result='',resultCode='',resultMsg=''  },
      } = yield call(service.modifyContactHistory,payload) || '';
      if(!resultCode || resultCode!=='0'){
        message.warn(resultMsg ||  'call api error');
        return;
      }
      message.success('Saved Successfully.');
    },
    *getContactReasonHistory({ payload }, { call, put }) {
      const {
        data: { result:{reasonHistorys=[]}='',resultCode='',resultMsg=''  },
      } = yield call(service.getContactReasonHistory,payload) || '';
      if(!resultCode || resultCode!=='0'){
        message.warn(resultMsg || 'call api error');
        return;
      }
      yield put({ type: 'save',payload:{reasonHistorys} });
    },
    *queryPhoneNum({ payload }, { call, put }) {
      const {timestamp=''}=payload;
      const {
        data: { result:inboundCallData='',resultCode='',resultMsg='' },
      } = yield call(service.queryPhoneNum,timestamp) || '';
      if(!resultCode || resultCode!=='0'){
        message.warn(resultMsg || 'call api error');
        return;
      }
      yield put({ type: 'save',payload:{inboundCallData} });
    },
    *createListRecord({ payload }, { call, put }) {
      const {
        data: {resultCode='',resultMsg='' },
      } = yield call(service.createListRecord,payload) || '';
      if(!resultCode || resultCode!=='0'){
        message.warn(resultMsg || 'call api error');
      }
    },
    *makeCall({ payload }, { call, put }) {
      const {
        data: { result:{makeCallResult:{uccid='',callMsg=''}=''}='',resultCode='',resultMsg='' },
      } = yield call(service.makeCall,payload) || '';
      if(!resultCode || resultCode!=='0'){
        message.warn(resultMsg || 'call api error');
        return null;
      }
      return {uccid,callMsg};
    },
    *getContactReason({ payload }, { call, put }) {
      const {uccid=''}=payload;
      const {
        data: { result:feedBackContactReasonData='',resultCode='',resultMsg='' },
      } = yield call(service.getContactReason,uccid) || '';
      if(!resultCode || resultCode!=='0'){
        message.warn(resultMsg || 'call api error');
      }
      yield put({ type: 'save',payload:{feedBackContactReasonData} });
    },
    *fetchAssociatesList({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      const {
        data: { result },
      } = yield call(service.getAssociatesList, { ...payload });

      yield put({
        type: 'associatesListSave',
        payload: result,
      });
    },
    *fetchPreferenceInfo({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: true,
        },
      });
      const {
        data: { result },
      } = yield call(service.getPreferenceInfo, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: false,
        },
      });
      yield put({
        type: 'preferenceInfoSave',
        payload: result,
      });
    },
    *fetchHotelBookingSummarize({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      // yield put({
      //   type: 'spinLoading/setLoadingFlag',
      //   payload: {
      //     voucherLoadingFlag: true,
      //   },
      // });
      const {
        data: { result },
      } = yield call(service.getHotelBookingSummarize, payload);
      yield put({
        type: 'save',
        payload: {
          hotelBookingSummarize: result,
        },
      });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: false,
        },
      });
    },
    *fetchvouchers({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: true,
        },
      });
      const {
        data: { result },
      } = yield call(service.getVouchers, { ...payload });
      // yield put({
      //   type: 'spinLoading/setLoadingFlag',
      //   payload: {
      //     voucherLoadingFlag: false,
      //   },
      // });
      yield put({
        type: 'vouchersSave',
        payload: result,
      });
    },
    *fetchCardDetail({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          cardDetailLoadingFlag: true,
        },
      });
      const {
        data: { result, resultCode },
      } = yield call(service.getCustomersCardDetail, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          cardDetailLoadingFlag: false,
        },
      });
      yield put({
        type: 'cardDetailSave',
        payload: result,
      });
      return result;
    },
    *fetchCompBalance({payload},{call,put}){
      let {
        data: { resultCode, resultMsg, result = {} },
      } = yield call(service.fetchCompBalance,payload);
      if (resultCode === '0') {
        yield put({
          type: 'save',
          payload: {
            compBalance: result.compBalance,
          },
        });
      } else throw resultMsg;
    },
    *fetchTransactionLogs({ payload }, { call, put }) {
      const queryType = payload.queryType;
      const transType = payload.transType;
      yield put({ type: 'global/refreshSessionTime' });
      if (queryType === 'current') {
        if (transType === 1) {
          yield put({
            type: 'spinLoading/setLoadingFlag',
            payload: {
              currentVoucherLoadingFlag: true,
            },
          });
          yield put({
            type: 'resetErrFlag',
            payload: {
              voucherTransErrorFlag: false,
            },
          });
        } else if (transType === 2) {
          yield put({
            type: 'spinLoading/setLoadingFlag',
            payload: {
              currentHotelLoadingFlag: true,
            },
          });
          yield put({
            type: 'resetErrFlag',
            payload: {
              hotelTransErrorFlag: false,
            },
          });
        }
      } else {
        yield put({
          type: 'spinLoading/setLoadingFlag',
          payload: {
            voucherTransLoadingFlag: true,
          },
        });
        yield put({
          type: 'resetErrFlag',
          payload: {
            voucherTransErrorFlag: false,
          },
        });
      }

      const {
        data: { result, resultCode },
      } = yield call(service.getTransactionLogs, { ...payload });
      yield put({
        type: 'spin/save',
        payload: {
          loading: false,
        },
      });
      if (queryType === 'current') {
        if (transType === 1) {
          yield put({
            type: 'spinLoading/setLoadingFlag',
            payload: {
              currentVoucherLoadingFlag: false,
            },
          });
        } else if (transType === 2) {
          yield put({
            type: 'spinLoading/setLoadingFlag',
            payload: {
              currentHotelLoadingFlag: false,
            },
          });
        }
      } else {
        yield put({
          type: 'spinLoading/setLoadingFlag',
          payload: {
            voucherTransLoadingFlag: false,
          },
        });
      }
      /*  if(resultCode === 0){*/
      yield put({
        type: 'transactionLogsSave',
        payload: result,
        transType: payload.transType,
        resultCode: resultCode,
        queryType: payload.queryType,
      }); /*else if(payload.transType === 1){

        const voucherTrans = [];
        const hotelTrans = [];
        const allTransactions = [];
        const hasData = false;
        return {
          voucherTrans,hotelTrans,allTransactions,hasData,
        }
      }*/
      /* } */
    },
    *fetchRemoveList({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          favoriteLoadingFlag: true,
        },
      });
      const { data } = yield call(service.getRemoveList, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          favoriteLoadingFlag: false,
        },
      });
      if (data.resultCode == '0') {
        yield put({
          type: 'save',
          payload: { isFavorite: 0 },
        });
        yield put({
          type: 'removeSuccess',
          payload: data.resultMsg,
        });
      } else {
        yield put({
          type: 'removeFailure',
          msg: data.resultMsg,
        });
      }
    },
    *fetchAddList({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          favoriteLoadingFlag: true,
        },
      });
      const { data } = yield call(service.getAddList, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          favoriteLoadingFlag: false,
        },
      });
      if (data.resultCode == '0') {
        yield put({
          type: 'save',
          payload: { isFavorite: 1 },
        });
        yield put({
          type: 'addSuccess',
          payload: data.resultMsg,
        });
      } else {
        yield put({
          type: 'addFailure',
          msg: data.resultMsg,
        });
      }
    },
    *fetchCustomerAuthority({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      const { data } = yield call(service.getUserAuthorities, payload);
      if(data){
        const authoritiesArray = data.map(authority => authority.privCode);
        let createAccess = false;
        if (authoritiesArray.includes('ACTIVITY_MANAGEMENT_F_CREATE')) {
          createAccess = true;
        }
        yield put({
          type: 'save',
          payload: {
            createAccess
          },
        });
      }
      yield put({
        type: 'checkUserAccess',
        payload: data,
      });
      yield put({
        type: 'save',
        payload: {
          authorities: data,
        },
      });
    },
    *fetchStatisticsList({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          statisticsLoadingFlag: true,
        },
      });
      const {
        data: { result },
      } = yield call(service.getStatisticsList, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          statisticsLoadingFlag: false,
        },
      });
      yield put({
        type: 'StatisticsListlSave',
        payload: result,
      });
    },
    *fetchCurrentHotel({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          hotelLoadingFlag: true,
        },
      });
      const {
        data: { result },
      } = yield call(service.getCurrentHotel, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          hotelLoadingFlag: false,
        },
      });
      yield put({
        type: 'hotelInfoSave',
        payload: result,
      });
    },
    *fetchAttractionPassInfo({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          cardDetailLoadingFlag: true,
        },
      });
      const {
        data: { result },
      } = yield call(service.getAttractionPassInfos, { ...payload });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          cardDetailLoadingFlag: false,
        },
      });
      yield put({
        type: 'passCardSave',
        payload: result,
      });
    },
    *fetchCustomerAttributeList({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: true,
        },
      });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getCustomerAttributeList, { ...payload });
      if (resultCode == '0') {
        let attributeList = result ? result.attributeList : null;
        if (!attributeList) {
          return;
        }
        let userName = window.AppGlobal && window.AppGlobal.userName;
        let userId = window.AppGlobal && window.AppGlobal.userId;
        if (!userName) {
          userName = 'admin';
        }
        if (!userId) {
          userId = 1000012;
        }
        for (let i = 0; i < attributeList.length; i++) {
          let iconName = '';
          let iconTitle = '';
          attributeList.editFlag = false; // 编辑模式 false

          if (attributeList[i].values) {
            let bookList = attributeList[i].values;
            let newBookList = [];
            for (let bookItem of bookList) {
              let tagStr = 'By ' + bookItem.operator;
              if (bookItem.modifyTime && bookItem.modifyTime != null) {
                let timeStr = moment(bookItem.modifyTime, 'YYYYMMDDhhmmss').format(
                  'DD-MMM-YYYY HH:mm:ss',
                );
                tagStr += ' on ' + timeStr;
              } else {
                let timeStr = moment(bookItem.createTime, 'YYYYMMDDhhmmss').format(
                  'DD-MMM-YYYY HH:mm:ss',
                );
                tagStr += ' on ' + timeStr;
              }
              bookItem.showTagStr = tagStr;
              bookItem.operation = 'M';
              bookItem.newDataFlag = false;
              bookItem.oldValue = bookItem.value;
              if (userId == bookItem.operatorId) {
                bookItem.editAble = true;
              } else {
                bookItem.editAble = false;
              }
              newBookList.push(bookItem);
            }
            attributeList.values = newBookList;
          }

          switch (attributeList[i].attrName) {
            case 'Gaming / Salon Set Up': {
              iconName = 'iconfont rws-Gaming-';
              iconTitle = 'Gaming';
              break;
            }
            case 'Food And Beverage Details': {
              iconName = 'iconfont rws-FB-';
              iconTitle = 'Food';
              break;
            }
            case 'Personal Details': {
              iconName = 'iconfont rws-person-';
              iconTitle = 'Personal';
              break;
            }
            case 'Lifestyle Preference': {
              iconName = 'iconfont rws-lifestyle-';
              iconTitle = 'Lifestyle';
              break;
            }
            case 'Hotel Set Up': {
              iconName = 'iconfont rws-hotel-';
              iconTitle = 'Hotel';
              break;
            }
            case 'Business Details': {
              iconName = 'iconfont rws-business-';
              iconTitle = 'Business';
              break;
            }
          }
          attributeList[i].showIconName = iconName;
          attributeList[i].showIcon = iconTitle;
        }
      } else {
        message.error(resultMsg);
      }
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: false,
        },
      });
      // console.log('customerAttributeListSave', result);
      yield put({
        type: 'customerAttributeListSave',
        payload: result,
      });
    },
    *fetchAttributeList({ payload }, { call, put }) {
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getAttributeList, { ...payload });
      if (resultCode == '0') {
        let attributeList = result ? result.attributeList : null;
        if (!attributeList) {
          return;
        }
        for (let i = 0; i < attributeList.length; i++) {
          let iconName = '';
          let iconTitle = '';
          let classNameStr = '';
          attributeList.editFlag = false; // 编辑模式 false
          switch (attributeList[i].attrName) {
            case 'Gaming / Salon Set Up': {
              iconName = 'iconfont rws-Gaming-';
              iconTitle = 'Gaming';
              classNameStr = 'commonBlackBookDiv';
              break;
            }
            case 'Food And Beverage Details': {
              iconName = 'iconfont rws-FB-';
              iconTitle = 'Food';
              classNameStr = 'commonBlackBookDiv';
              break;
            }
            case 'Personal Details': {
              iconName = 'iconfont rws-person-';
              iconTitle = 'Personal';
              classNameStr = 'bookDetailCar';
              break;
            }
            case 'Lifestyle Preference': {
              iconName = 'iconfont rws-lifestyle-';
              iconTitle = 'Lifestyle';
              classNameStr = 'commonBlackBookDiv';
              break;
            }
            case 'Hotel Set Up': {
              iconName = 'iconfont rws-hotel-';
              iconTitle = 'Hotel';
              classNameStr = 'commonBlackBookDiv';
              break;
            }
            case 'Business Details': {
              iconName = 'iconfont rws-business-';
              iconTitle = 'Business';
              classNameStr = 'bookDetailCar';
              break;
            }
          }
          attributeList[i].showIconName = iconName;
          attributeList[i].showIcon = iconTitle;
          attributeList[i].classNameStr = classNameStr;
        }
        yield put({
          type: 'attributeListSave',
          payload: result,
        });
      } else {
        message.error(resultMsg);
      }
    },
    *fetchModfiyCustmerAttr({ payload }, { call, put, select }) {
      const customerId = payload.customerId;
      const search = payload.customerAttributeList;
      let reqAttributeList = [];
      for (let customerAttribute of search) {
        customerAttribute.editFlag = false;
        if (customerAttribute.values) {
          for (let bookItem of customerAttribute.values) {
            if (bookItem.operation == 'M' && bookItem.oldValue != bookItem.value) {
              bookItem.attrType = customerAttribute.attrType;
              bookItem.attrSubType = customerAttribute.attrSubType;
              bookItem.attrCode = customerAttribute.attrCode;
              reqAttributeList.push(bookItem);
            } else if (bookItem.operation == 'A') {
              bookItem.attrType = customerAttribute.attrType;
              bookItem.attrSubType = customerAttribute.attrSubType;
              bookItem.attrCode = customerAttribute.attrCode;
              reqAttributeList.push(bookItem);
            }
          }
        }
      }
      if (reqAttributeList.length === 0) {
        return;
      }
      let reqParam = {
        customerId: customerId,
        attributeList: reqAttributeList,
      };
      const { data } = yield call(service.getModifyCustmerAttr, { ...reqParam });

      if (data.resultCode == '0') {
        message.success(data.resultMsg);
        yield put({
          type: 'fetchCustomerAttributeList',
          payload: {
            customerId,
          },
        });
      } else {
        message.error(data.resultMsg);
      }
    },
    *fecthGetCustomerChangeTracking({ payload }, { call, put }) {
      yield put({
        type: 'historyLoadingSave',
        payload: {
          loading: true,
        },
      });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getCustomerChangeTracking, { ...payload });

      if (resultCode == '0') {
        let historyList = result ? result.historyList : [];
        if (!historyList || historyList == null) {
          historyList = [];
        }
        for (let i = 0; i < historyList.length; i++) {
          let timeStr = '';
          let prevStr = '';
          let postStr = '';
          let nextprevStr = '';
          let nextpostStr = '';
          if (historyList[i].createTime && historyList[i].createTime != null) {
            timeStr = moment(historyList[i].createTime, 'YYYYMMDDhhmmss').format(
              'DD-MMM-YYYY HH:mm:ss',
            );
          }
          if (historyList[i].prevValues && historyList[i].prevValues != null) {
            prevStr = historyList[i].prevValues;
            for (let j = 0; j < prevStr.length; j++) {
              nextprevStr += prevStr[j] + ',';
            }
            if (nextprevStr.substr(nextprevStr.length - 1, nextprevStr.length) == ',') {
              nextprevStr = nextprevStr.substr(0, nextprevStr.length - 1);
            }
          }
          if (historyList[i].postValues && historyList[i].postValues != null) {
            postStr = historyList[i].postValues;
            for (let j = 0; j < postStr.length; j++) {
              nextpostStr += postStr[j] + ',';
            }
            if (nextpostStr.substr(nextpostStr.length - 1, nextpostStr.length) == ',') {
              nextpostStr = nextpostStr.substr(0, nextpostStr.length - 1);
            }
          }
          historyList[i].createTime = timeStr;
          historyList[i].prevValues = nextprevStr;
          historyList[i].postValues = nextpostStr;
        }
        yield put({
          type: 'customerChangeTrackingSave',
          payload: result,
        });
        yield put({
          type: 'historyLoadingSave',
          payload: {
            loading: false,
          },
        });
      } else {
        message.error(resultMsg);
      }
    },
    // 修改客户 other casino
    *fetchModfiyCustmerOtherCasino({ payload }, { call, put }) {
      const customerId = payload.customerId;
      const userName = payload.userName;
      const userId = payload.userId;
      const customerOtherCasinoList = payload.customerOtherCasinoList;
      let reqList = [];
      for (let casino of customerOtherCasinoList) {
        if (
          casino.attrCode === casino.oldAttrCode &&
          casino.oldAttrValue === casino.attrValue &&
          casino.operation != 'D'
        ) {
          if (
            !casino.level ||
            (casino.level &&
              casino.level.attrCode == casino.level.oldAttrCode &&
              casino.level.attrValue === casino.level.oldAttrValue)
          ) {
            continue;
          }
        }
        let otherCasino = {
          casinoId: casino.casinoId,
          configId: casino.configId,
          attrType: casino.attrType,
          attrTypeName: casino.attrTypeName,
          attrCode: casino.attrCode,
          attrName: casino.attrName,
          attrValue: casino.attrValue,
          inputType: casino.inputType,
          visible: casino.visible,
          operator: userName,
          operatorId: userId,
          createTime: casino.createTime,
          modifyTime: casino.modifyTime,
          operation: casino.operation,
          level: {},
        };
        if (casino.level) {
          let level = {
            levelId: casino.level.levelId,
            attrCode: casino.level.attrCode,
            attrName: casino.level.attrName,
            attrValue: casino.level.attrValue,
            inputType: casino.level.inputType,
            visible: casino.level.visible,
            operator: userName,
            operatorId: userId,
            createTime: casino.level.createTime,
            modifyTime: casino.level.modifyTime,
            operation: casino.level.operation,
          };
          otherCasino.level = level;
        }
        reqList.push(otherCasino);
      }
      let result = 0;
      if (reqList.length === 0) {
        // message.error('Failed to modify, because there is no changing!');
        yield put({
          type: 'cancelEditState',
          payload: {},
        });
        return;
      }
      let reqParam = {
        customerId: customerId,
        otherCasinoList: reqList,
      };
      const { data } = yield call(service.getModifyCustmerOtherCasino, { ...reqParam });
      if (data.resultCode == '0') {
        message.success('Saved successfully.');
        yield put({
          type: 'fetchCustomerOtherCasinoInfo',
          payload: {
            customerId,
          },
        });
      } else {
        message.error(data.resultMsg);
      }
    },
    *getUserRegionsWithRmCodes({ payload }, { call, put }) {
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getUserRegionsWithRmCodes, { ...payload });

      if (resultCode == '0') {
        let userRegionWithRmCodeList = result ? result.userRegionWithRmCodeList : null;
        if (!userRegionWithRmCodeList) {
          return;
        }
        yield put({
          type: 'userRegionWithRmCodeListSave',
          payload: result,
        });
      } else {
        message.error(resultMsg);
      }
    },
    *fetchCustomerPreferenceInfo({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: true,
        },
      });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getCustomersPreference, { ...payload });
      if (resultCode == '0') {
        let customerPreferenceInfoList = result ? result.preferenceInfos : null;
        if (!customerPreferenceInfoList) {
          return;
        }
        let userName = window.AppGlobal && window.AppGlobal.userName;
        let userId = window.AppGlobal && window.AppGlobal.userId;
        if (!userName) {
          userName = 'admin';
        }
        if (!userId) {
          userId = 1000012;
        }
        for (let i = 0; i < customerPreferenceInfoList.length; i++) {
          let iconName = '';
          if (customerPreferenceInfoList[i].system === '100') {
            iconName = 'cloud';
          } else {
            switch (customerPreferenceInfoList[i].type) {
              case '1010': {
                iconName = 'iconfont rws-music';
                break;
              }
              case '1011': {
                iconName = 'iconfont rws-entertainment';
                break;
              }
              case '1012': {
                iconName = 'iconfont rws-sport';
                break;
              }
              case '1013': {
                iconName = 'iconfont rws-watch';
                break;
              }
              case '1014': {
                iconName = 'iconfont rws-fashion';
                break;
              }
              case '1015': {
                iconName = 'iconfont rws-FB-';
                break;
              }
              case '1016': {
                iconName = 'iconfont rws-alchol';
                break;
              }
              default: {
                iconName = 'iconfont rws-other';
                break;
              }
            }
          }
          customerPreferenceInfoList[i].showIconName = iconName;
          if (customerPreferenceInfoList[i].values) {
            for (let customerPreferenceV of customerPreferenceInfoList[i].values) {
              customerPreferenceV.newValue = false;
              customerPreferenceV.oldMessage = customerPreferenceV.message;
              customerPreferenceV.editAble = true;
              customerPreferenceV.showFlag = true;
              // cxm-348 权限调整，只要有widget权限就可以操作
              /*if (userId == customerPreferenceV.operatorId) {
                customerPreferenceV.editAble = true;
              }*/
              if (customerPreferenceInfoList[i].system !== '999') {
                customerPreferenceV.editAble = false;
              }
              customerPreferenceV.operation = 'N'; //无变化的值
            }
          }
        }
      } else {
        message.error(resultMsg);
      }
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          voucherLoadingFlag: false,
        },
      });
      yield put({
        type: 'customerPreferenceInfoSave',
        payload: result,
      });
    },
    *fetchCustomerOtherCasinoInfo({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          customerDetailLoadingFlag: true,
        },
      });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getCustomersOtherCasino, { ...payload });
      if (resultCode == '0') {
        let customerOtherCasinoList = result ? result.otherCasinoList : null;
        if (!customerOtherCasinoList) {
          return;
        }
      }
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          customerDetailLoadingFlag: false,
        },
      });
      // console.log('customerOtherCasinoInfoSave', result);
      yield put({
        type: 'customerOtherCasinoInfoSave',
        payload: result,
      });
    },
    *fetchCustomerOtherCasinoConfigInfo({ payload }, { call, put }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          customerDetailLoadingFlag: true,
        },
      });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getCustomersOtherCasinoConfig, { ...payload });
      if (resultCode == '0') {
        let configList = result ? result.configList : [];
        let customerOtherCasinoConfigList = [];
        if(configList.length>0){
          customerOtherCasinoConfigList = configList[0].subList;
        }
/*        let customerOtherCasinoConfigList =
          result && result.configList && result.configList[0].subList? result.configList[0].subList : null;*/
        if (!customerOtherCasinoConfigList || customerOtherCasinoConfigList.length === 0) {
          return;
        }
        yield put({
          type: 'customerOtherCasinoConfigInfoSave',
          payload: result,
        });
      }
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          customerDetailLoadingFlag: false,
        },
      });
      // console.log('customerOtherCasinoConfigInfoSave', result);
/*      yield put({
        type: 'customerOtherCasinoConfigInfoSave',
        payload: result,
      });*/
    },
    *fecthGetCustomerPreferenceChangeTracking({ payload }, { call, put }) {
      yield put({
        type: 'historyLoadingSave',
        payload: {
          loading: true,
        },
      });
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getPreferenceChangeTracking, { ...payload });

      if (resultCode == '0') {
        let historyList = result ? result.historyList : [];
        if (!historyList || historyList == null) {
          historyList = [];
        }
        for (let i = 0; i < historyList.length; i++) {
          let timeStr = '';
          let prevStr = '';
          let postStr = '';
          let nextprevStr = '';
          let nextpostStr = '';
          if (historyList[i].createTime && historyList[i].createTime != null) {
            timeStr = moment(historyList[i].createTime, 'YYYYMMDDhhmmss').format(
              'DD-MMM-YYYY HH:mm:ss',
            );
          }
          if (historyList[i].prevValues && historyList[i].prevValues != null) {
            prevStr = historyList[i].prevValues;
            for (let j = 0; j < prevStr.length; j++) {
              nextprevStr += prevStr[j] + ',';
            }
            if (nextprevStr.substr(nextprevStr.length - 1, nextprevStr.length) == ',') {
              nextprevStr = nextprevStr.substr(0, nextprevStr.length - 1);
            }
          }

          if (historyList[i].postValues && historyList[i].postValues != null) {
            postStr = historyList[i].postValues;
            for (let j = 0; j < postStr.length; j++) {
              nextpostStr += postStr[j] + ',';
            }
            if (nextpostStr.substr(nextpostStr.length - 1, nextpostStr.length) == ',') {
              nextpostStr = nextpostStr.substr(0, nextpostStr.length - 1);
            }
          }
          historyList[i].createTime = timeStr;
          historyList[i].prevValues = nextprevStr;
          historyList[i].postValues = nextpostStr;
        }

        yield put({
          type: 'customerChangeTrackingSave',
          payload: result,
        });
        yield put({
          type: 'historyLoadingSave',
          payload: {
            loading: false,
          },
        });
      } else {
        message.error(resultMsg);
      }
    },
    *fetchPreferenceConfig({ payload }, { call, put }) {
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getPreferenceConfig, { ...payload });
      if (resultCode === '0') {
        let configList = result ? result.configList : [];
        let subTypeList = [];
        if(configList && configList.length>0){
          subTypeList = configList[0].subList;
        }
        for (let i = 0; i < subTypeList.length; i++) {
          let iconName = '';
          switch (subTypeList[i].subType) {
            case '1010': {
              iconName = 'iconfont rws-music';
              break;
            }
            case '1011': {
              iconName = 'iconfont rws-entertainment';
              break;
            }
            case '1012': {
              iconName = 'iconfont rws-sport';
              break;
            }
            case '1013': {
              iconName = 'iconfont rws-watch';
              break;
            }
            case '1014': {
              iconName = 'iconfont rws-fashion';
              break;
            }
            case '1015': {
              iconName = 'iconfont rws-FB-';
              break;
            }
            case '1016': {
              iconName = 'iconfont rws-alchol';
              break;
            }
            default: {
              iconName = 'iconfont rws-other';
              break;
            }
          }
          subTypeList[i].showIconName = iconName;
        }
        yield put({
          type: 'save',
          payload: {
            preferenceConfigList: subTypeList,
          },
        });
      } else {
        message.error(resultMsg);
      }
    },
    *fetchModifyCustomersPreference({ payload }, { call, put, select }) {
      let userName = window.AppGlobal && window.AppGlobal.userName;
      let userId = window.AppGlobal && window.AppGlobal.userId;
      if (!userName) {
        userName = 'admin';
      }
      if (!userId) {
        userId = 1000012;
      }

      const customerId = payload.customerId;
      const customerPreferenceInfoList = payload.customerPreferenceInfoList;

      let reqData = {
        customerId: customerId,
        operator: userName,
        operatorId: userId,
        preferenceInfos: [],
      };

      for (let customerPreference of customerPreferenceInfoList) {
        let changeCustomerPreference = null;
        let changeCustomerValues = [];
        if (customerPreference.system === '999' && customerPreference.values) {
          for (let customerValue of customerPreference.values) {
            if (customerValue.operation === 'A' && customerValue.showFlag) {
              changeCustomerPreference = {}; // 本次想新增的
              if (customerValue.messageType == 2) {
                customerValue.message = customerValue.messageItem;
              }
              changeCustomerValues.push(customerValue);
            } else if (customerValue.operation === 'M' && customerValue.showFlag) {
              changeCustomerPreference = {}; // 原有是展示的，但是被修改了
              if (customerValue.messageType == 2) {
                customerValue.message = customerValue.messageItem;
              }
              changeCustomerValues.push(customerValue);
            } else if (customerValue.operation === 'N' && !customerValue.showFlag) {
              changeCustomerPreference = {}; // 原有展示，修改后被删除了
              customerValue.operation = 'D';
              if (customerValue.messageType == 2) {
                customerValue.message = customerValue.messageItem;
              }
              changeCustomerValues.push(customerValue);
            }
          }
        }
        if (changeCustomerPreference) {
          changeCustomerPreference.type = customerPreference.type;
          // changeCustomerPreference.subType = customerPreference.subType;
          changeCustomerPreference.values = changeCustomerValues;
          reqData.preferenceInfos.push(changeCustomerPreference);
        }
      }

      if (reqData.preferenceInfos && reqData.preferenceInfos.length === 0) {
        return; //无数据变更
      }

      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.modifyCustomersPreference, { ...reqData });
      if (resultCode === '0') {
        message.success('Saved successfully.');
        // 成功后刷新数据，保证summary数据显示出最新的配置
        yield put({
          type: 'fetchCustomerPreferenceInfo',
          payload: {
            customerId,
          },
        });
      } else {
        message.error(resultMsg);
      }
    },
    //hotllog 查询
    *hotelLogSearch({ payload }, { call, put }) {
      // 刷新后台Session
      yield put({ type: 'global/refreshSessionTime' });
      // 开启加载动画
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          cardDetailLoadingFlag: true,
        },
      });
      // Hotel搜索
      const {
        data: { result, resultCode },
      } = yield call(service.hotelSearch, { ...payload });

      let hotelLogInfos = result.hotelLogInfos;
      let idsArr = new Set();
      if (hotelLogInfos && hotelLogInfos.length > 0) {
        for (let i = 0; i < hotelLogInfos.length; i++) {
          idsArr.add(hotelLogInfos[i].userId);
        }
      }
      const ids = Array.from(idsArr).join(',');
      // 用户用户名搜索
      const {
        data,
      } = yield call(service.queryUserNameById, ids);

      // 关闭加载动画
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          cardDetailLoadingFlag: false,
        },
      });
      yield put({
        type: 'setOperaList',
        payload: result,
      });
      yield put({
        type: 'saveUserMessage',
        payload: data,
      });
    },
    *fetchOutstandingList({ payload }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          outstandingLoading: true,
        },
      });
      const param = {
        currentPage: 1,
        pageSize: 5,
        ...payload,
      };
      const {
        data: { resultCode, resultMsg, result },
      } = yield call(service.getOutstandingList, param);
      if (resultCode === '0') {
        const { outTaskList } = result;
        yield put({
          type: 'save',
          payload: {
            outstandingList: outTaskList,
            outstandingLoading: false,
            outstandingTotal: result.totalSize,
            outstandingCurrent: param.currentPage,
            outstandingPageSize: param.pageSize,
          },
        });
      } else {
        yield put({
          type: 'save',
          payload: {
            outstandingList: [],
            outstandingLoading: false,
          },
        });
      }
    },
    *handleOutstandingDetail({ payload }, { put }) {
      yield put({
        type: 'save',
        payload: {
          ...payload,
        },
      });
    },
    *fetchActivityTypeList(_, { put, call }) {
      const data = {
        dictType: '10',
        dictSubType: '10',
      };
      const {
        data: { resultCode, result },
      } = yield call(service.getDictionaryConfig, data);
      if (resultCode === '0') {
        const { dictList } = result;
        yield put({
          type: 'save',
          payload: {
            activityTypeList: dictList,
          },
        });
      }
    },
    *fetchStatusInfo(_, { put, call }) {
      const data = {
        dictType: '30',
        dictSubType: '14',
      };
      const {
        data: { resultCode, result },
      } = yield call(service.getDictionaryConfig, data);
      if (resultCode === '0') {
        const statusList = [];
        const { dictList } = result;
        dictList.map(e => {
          const { dictId } = e;
          if (dictId !== '3014003' && dictId !== '3014004') {
            statusList.push(e);
          }
          return e;
        });
        yield put({
          type: 'save',
          payload: {
            statusList,
          },
        });
      }
    },
    *setResult({ payload }, { call, select, put }) {
      const {
        detailOutstandingInfo: {
          taskInfo: { id, resultDesc, dncFlag, customerName,grmemberNo='',rmGroup='' },
          basicInfo: { dncExpiredFlag,campaignId='' }
        },
        customerInfo: { customerId },
        outstandingCurrent,
        outstandingPageSize,
      } = yield select(state => state.customerView);
      if (dncExpiredFlag === 1) {
        message.warn('The campaign reaches DNC Expired Date.You cannot set result.');
        return;
      }
      const data = {
        cxmid: customerId,
        objectId: id,
        resultFlag: 'RSVP',
        resultContent: 'set result',
        operator: window.AppGlobal.userName,
        operatorId: window.AppGlobal.userId,
        campaignId,
        grmemberNo,
        rmGroup,
        ...payload,
      };
      //有错误
      const {
        data: { resultCode },
      } = yield call(service.setResult, { feedbackList: [data] });
      if (resultCode === '0') {
        message.success('Modified successfully');
        // yield put({
        //   type: 'fetchOutstandingList',
        //   payload: {
        //     currentPage: outstandingCurrent,
        //     pageSize: outstandingPageSize,
        //     cxmid: customerId,
        //   },
        // });
        yield put({
          type: 'fetchEligibilityList',
          payload: {
            cxmid: customerId,
          },
        });
      } else {
        message.success('Failed to modify');
      }
    },
    *searchEventByCampaignId({ payload }, { call, put, }) {
      const { data:{result:{campaignList=[]}='' ,resultCode='',resultMsg=''}='' } = yield call(campaignService.getCampaignList, payload);
      if (!resultCode || resultCode !== '0'){
        message.warn(resultMsg|| 'searchEventByCampaignId api error');
      }
      const eventSessionList=[];
      if(campaignList && campaignList.length>0){
        campaignList.forEach(item=>{
          let pax='';
          let eventSelect=false;
          const {eventSessions=[],campaignAttrs=[],campaignId,campaignName}=item;
          const eventSessionshandle = [];
          if(eventSessions && eventSessions.length>0){
            eventSessions.forEach(item=> eventSessionshandle.push({...item,modify:true}));
          }
          if(campaignAttrs && campaignAttrs.length>0){
            campaignAttrs.forEach(attr=>{
              if(attr.key==='EVENT_DEFAULT_PAX_NO') pax = attr.value || '';
              if(attr.key==='EVENT_SELECT' && attr.value==='Yes') eventSelect = true;
            });
          }
          const child ={eventSelect,defaultPax:pax,eventSessions:eventSessionshandle,campaignId,campaignName};
          eventSessionList.push(child);
        })
      }
        yield put({ type: 'save', payload: { eventSessionList}});
    },
    *queryCustConsideration({ payload }, { call, put, }) {
      const { data: { result:{consideration:tempConsideration=[]} = '', resultCode='',resultMsg='' } = '' } = yield call(taskCenterService.queryCustConsideration, payload);
      if (!resultCode || resultCode !== '0'){
        message.warn(resultMsg|| 'queryCustConsideration api error');
        return;
      }
      let consideration = [];
      if(tempConsideration){consideration = tempConsideration}
      yield put({ type: 'save', payload: { consideration }});
    },
    //跳转路由到预定酒店界面
    *pathToBooking({ payload }, { put }) {
      const { customerId } = payload;
      yield put(routerRedux.push(`/hotel/reserve/${customerId}`));
    },
    * fetchNBOList({ payload }, { call, put, select }) {
      yield put({ type: 'global/refreshSessionTime' });
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          nboLoadingFlag: true,
        },
      });
      let {
        data: {
          resultCode,
          result: { attributeList = [] },
        },
      } = yield call(service.getNBOList, payload);
      yield put({
        type: 'spinLoading/setLoadingFlag',
        payload: {
          nboLoadingFlag: false,
        },
      });
      if (resultCode === '0') {
        const { grInfo } = yield select(state => state.customerView);
        if (!grInfo || !grInfo.grMembNo) {
          attributeList = attributeList.filter(item => item.attrName != 'Casino Chip/Warrant - Program');
        }
        yield put({
          type: 'nboListlSave',
          payload: {
            nboInfoList: attributeList,
          },
        });
      } else {
        yield put({
          type: 'nboListlSave',
          payload: {},
        });
      }
    },
    *fetchTaskTabActiveKeyChange({ payload }, { call, put, select }) {
      yield put({
        type: 'save',
        payload: {
          taskTabActiveKey: payload.activeKey,
        },
      });
    },
    *fetchQueryDictionaryByStatus({ payload }, { call, put, select }){
      let reqParam = {
        dictType: 80,
        dictSubType: 9,
      };
      const {
        data: { result, resultCode, resultMsg },
      } = yield call(service.getDictionaryConfig, { ...reqParam });
      if (resultCode === '0') {
        if (result && result.dictList) {
          yield put({
            type: 'save',
            payload: {
              activityManualStatusList: result.dictList,
            },
          });
        }
      } else throw resultMsg;

    },
    *fetchQueryDictionaryActivityType({ payload }, { call, put, select }){
      let reqParam = {
        dictType: 80,
        dictSubType: 3,
      };
      const {
        data: { result, resultCode, resultMsg },
      } = yield call(service.getDictionaryConfig, { ...reqParam });
      if (resultCode === '0') {
        if (result && result.dictList) {
          yield put({
            type: 'save',
            payload: {
              activityManualTypeList: result.dictList,
            },
          });
        }
      } else throw resultMsg;
    },
    *fetchQueryDictionaryActivitySubType({ payload }, { call, put, select }){
      let reqParam = {
        dictType: 80,
        dictSubType: 4,
      };
      const {
        data: { result, resultCode, resultMsg },
      } = yield call(service.getDictionaryConfig, { ...reqParam });
      if (resultCode === '0') {
        if (result && result.dictList) {
          yield put({
            type: 'save',
            payload: {
              activityManualSubTypeList: result.dictList,
            },
          });
        }
      } else throw resultMsg;
    },
    *fetchManualGetOutstandingList({ payload }, { call, put, select }){
      let reqParam ={
        currentPage: 1,
        pageSize: 5,
        vipRole:'2',
        ...payload,
      };
      const {
        data: { result, resultCode, resultMsg },
      } = yield call(service.getManualOutstandingList, { ...reqParam });
      if (resultCode === '0') {
        let outTaskList = result.outTaskList;
        let manualActivityList =[];
        let {
          authorities,
          userGroupingList
        } = yield select(state => state.customerView);
        const authoritiesArray = authorities.map(authority => authority.privCode);

        let userId = window.AppGlobal && window.AppGlobal.userId;
        if (!userId) {
          userId = 1000012;
        }
        for(let taskObj of outTaskList){
          let showManualObj = {...taskObj.activityInfo};
          showManualObj.detailBtnFlag = false;
          showManualObj.editBtnFlag = false;
          showManualObj.pickUpBtnFlag = false;
          showManualObj.copyBtnFlag = false;
          showManualObj.cancelBtnFlag = false;
          showManualObj.closeBtnFlag = false;
          showManualObj.subTypeFlag = true;
          if ( authoritiesArray.includes('ACTIVITY_MANAGEMENT_F_VIEW') ){
            showManualObj.detailBtnFlag = true;
          }
          if ( authoritiesArray.includes('ACTIVITY_MANAGEMENT_F_COPY') ){
            showManualObj.copyBtnFlag = true;
          }
          if (String(userId) === String(showManualObj.operatorId)){
            if(showManualObj.statusCode === '3014001'){
              showManualObj.editBtnFlag = true;
              showManualObj.cancelBtnFlag = true;
            }
          }
          if(showManualObj.subActivityType === '8004000'){
            showManualObj.subTypeFlag =false;
          }

          // creator group owner
          let isCreatorGroupOwner = false;
          let isAssignUser = false;
          let isAssignGroupOwner = false;
          let isAssignGroupMember = false;
          let isCreatorGroupMember = false;
          let isHandler = false;
          let assignType = 0; // 0-group , 1-user

          for (const userGroup of userGroupingList){
            if (userGroup.status !==0) {
              continue;
            }
            let userInThisGroup = false;
            let creatorInThisGroup = false;
            let userIsThisGroupOwner = false;
            let assignUserInGroup = false;
            for (const memberInfo of userGroup.members){
              if (String(memberInfo.userId) === String(userId)){
                userInThisGroup = true;
                if (memberInfo.isOwner === 1){
                  userIsThisGroupOwner = true;
                }
              }else if (String(memberInfo.userId) === String(showManualObj.operatorId)){
                creatorInThisGroup = true;
              }
              if (userInThisGroup && creatorInThisGroup) {
                if (userIsThisGroupOwner){
                  isCreatorGroupOwner = true;
                } else {
                  isCreatorGroupMember = true;
                }
              }
              for (const taskObj of showManualObj.taskList) {
                if (taskObj && taskObj.resultCode==="1"){
                  continue;
                }
                if (taskObj.dealerType === "1" && (String(taskObj.dealerId) === String(userId))) {
                  isAssignUser = true;
                  showManualObj.assignTask = taskObj;
                  if (taskObj.status === '3015005'){
                    isHandler = true;
                    showManualObj.handleTask = taskObj;
                  }
                  assignType = 1;
                } else if (taskObj.dealerType === "0" && (String(taskObj.dealerId) === String(userGroup.id))){
                  if (userIsThisGroupOwner){
                    isAssignGroupOwner = true;
                    showManualObj.assignTask = taskObj;
                  } else if (userInThisGroup){
                    isAssignGroupMember = true;
                    showManualObj.assignTask = taskObj;
                  }
                  assignType = 0;
                } else if (taskObj.dealerType === "1" && (String(taskObj.dealerId) === String(memberInfo.userId))){
                  assignUserInGroup = true;
                  showManualObj.assignTask = taskObj;
                  assignType = 1;
                }
              }
            }
            if (assignUserInGroup && userIsThisGroupOwner) {
              isAssignGroupOwner = true;
            }
          }
          if (showManualObj.statusCode !== '3014001' && isHandler){
            if(showManualObj.statusCode === '3014002'){
              showManualObj.editBtnFlag = true;
              showManualObj.closeBtnFlag = true;
            }
          } else if (isCreatorGroupOwner){
            if(showManualObj.statusCode === '3014001'){
              showManualObj.editBtnFlag = true;
              showManualObj.cancelBtnFlag = true;
            }
          }
          if (isAssignUser){
            if(showManualObj.statusCode === '3014001'){
              showManualObj.pickUpBtnFlag = true;
            }
          } else if (isAssignGroupOwner){
            if(showManualObj.statusCode === '3014001' && assignType === 0){
              showManualObj.pickUpBtnFlag = true;
            } else if(showManualObj.statusCode === '3014002'){
              showManualObj.editBtnFlag = true;
            }
          } else if (isAssignGroupMember){
            if(showManualObj.statusCode === '3014001' && assignType === 0){
              showManualObj.pickUpBtnFlag = true;
            }
          } else if (isCreatorGroupMember){
            // only see detail
          }

          showManualObj.assigner = '';
          showManualObj.pickedUp = '';
          showManualObj.pickedUpDate = '';
          for (const taskObj of showManualObj.taskList) {
            if (!taskObj || resultCode==="0"){
              if (taskObj.status === '3015001'){
                showManualObj.assigner += '@' + taskObj.dealer + ' ';
              }
              if ((!taskObj || resultCode==="0") && taskObj.status === '3015005'){
                showManualObj.pickedUp = taskObj.dealer;
                showManualObj.pickedUpDate = moment(taskObj.createdTime , 'YYYYMMDDhhmmss').format('DD-MMM-YYYY HH:mm:ss');
              }
            }
          }
          if(showManualObj.createdDate && showManualObj.createdDate != null){
            showManualObj.createdDate = moment(showManualObj.createdDate , 'YYYYMMDDhhmmss').format('DD-MMM-YYYY HH:mm:ss');
          }
          if(showManualObj.plandedCompletedDate && showManualObj.plandedCompletedDate != null){
            showManualObj.plandedCompletedDate = moment(showManualObj.plandedCompletedDate , 'YYYYMMDDhhmmss').format('DD-MMM-YYYY HH:mm:ss');
          }
          if(showManualObj.priority && showManualObj.priority != null){
            if(showManualObj.priority === '8001003'){
              showManualObj.backgroundColor = '#FFECEA';
              showManualObj.priorityColor = '#88160A';
            }
            else if(showManualObj.priority === '8001002'){
              showManualObj.backgroundColor = '#FFF0CF';
              showManualObj.priorityColor = '#DC9500';
            }
            else if(showManualObj.priority === '8001001'){
              showManualObj.backgroundColor = '#DEEFF8';
              showManualObj.priorityColorr = '#259DDB';
            }
          }
          if(showManualObj.statusCode && showManualObj.statusCode != null){
            if(showManualObj.statusCode === '3014001'){
              showManualObj.styleName  = { border: '#FFBB96 1px solid', color: '#FA541C' };
            }
            else if(showManualObj.statusCode === '3014002'){
              showManualObj.statusDesc = 'Picked Up';
              showManualObj.styleName  = { border: '#2F9BFF 1px solid', color: '#1890FF' };
            }
            else if(showManualObj.statusCode === '3014003'){
              showManualObj.styleName  = { border: '#22B400 1px solid', color: '#22B400' };
            }
            else if(showManualObj.statusCode === '3014004'){
              showManualObj.styleName  = { border: '#C8C8C8 1px solid', color: '#A8A8A8' };
            }
          }
          manualActivityList.push(showManualObj);
        }
        yield put({
          type: 'save',
          payload: {
            manualActivityTotal: result.totalSize ? result.totalSize : 0,
            manualActivityList: manualActivityList,
            manualActivityCurrent: reqParam.currentPage,
            manualActivityPageSize: reqParam.pageSize,
          },
        });

      }else throw resultMsg;

    },
    *fetchUserGroupingList({ payload }, { call, put, select }) {
      let reqParam = {
        groupType: 10,
      };
      const {
        data: { userGroupInfos, resultCode, resultMsg },
      } = yield call(service.queryUserGroupsWithMembers, { ...reqParam });
      if (resultCode === '0') {
        if ( userGroupInfos ){
          yield put({
            type: 'save',
            payload: {
              userGroupingList: userGroupInfos
            },
          });
        }
      } else {
        message.error(resultMsg);
      }
    },
    *fetchModifyActivityStatus({ payload }, { call, put, select }){
      let reqParam = {
      };
      if (payload) {
        reqParam = { ...reqParam, ...payload };
      }
      Object.keys(reqParam).forEach(function(key) {
        if (typeof reqParam[key] === 'string' && reqParam[key]) {
          reqParam[key] = reqParam[key].replace(/(^\s*)|(\s*$)/g, '');
        }
      });
      const {
        data: { result, resultCode, resultMsg },
      } = yield call(service.modifyActivityStatus, { ...reqParam });
      if (resultCode === '0'){
        message.success( payload.operation+" successfully.");
        yield put({
          type: 'fetchManualGetOutstandingList',
          payload: {
            cxmid: payload.cxmid,
            currentPage: 1,
            pageSize: payload.pageSize,
            activityType: payload.activityType,
            subActivityType: payload.subActivityType,
            activityStatus: payload.activityStatus,
          },
        });
      }else {
        message.error(resultMsg);
      }
    },
    *fetchMenu({ payload = {} }, { call, put, select }) {
      const { currentUser } = yield select(state => state.global);
      const { portalId } = currentUser;
      const { data } =  yield call(service.queryMenus, portalId);
      if (data) {
        let createAccessMenu = yield select(state => state.customerView.createAccessMenu);
        if (data.findIndex(item => String(item.type) === "1"  && String(item.partyName)==='Activity Management') !== -1) {
          createAccessMenu=true;
        }
        yield put({
          type: 'save',
          payload: {
            menuData: data,
            createAccessMenu
          },
        });
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },

    nboListlSave(state, { payload: { nboInfoList = [] } }) {
      return { ...state, nboInfoList };
    },

    // 校验用户角色权限
    checkUserAccess(state, { payload: data }) {
      let userAccessList = [];
      if (data) {
        for (let result of data) {
          let key = result.privCode;
          if (key == '10026') {
            userAccessList.push('GAMING_SALON_SET_UP');
          }
          if (key == '10027') {
            userAccessList.push('FOOD_AND_BEVERAGE_DETAILS');
          }
          if (key == '10028') {
            userAccessList.push('LIFESTYLE_PREFERENCE');
          }
          if (key == '10029') {
            userAccessList.push('HOTEL_SET_UP');
          }
          if (key == '10030') {
            userAccessList.push('PERSONAL_DETAILS');
          }
          if (key == '10031') {
            userAccessList.push('BUSINESS_DETAILS');
          }
        }
      }
      //console.log('userAccessList:' + userAccessList);
      return { ...state, userAccessList };
    },
    // 查询客户明细信息
    customerDetailSave(state, { payload: result }) {
      const oldCustomerInfo = state.customerInfo;
      const customerInfo = result.customerInfo;
      customerInfo.terminalInfos = customerInfo && customerInfo.terminalInfos ? customerInfo.terminalInfos : oldCustomerInfo.terminalInfos;
      customerInfo.customerPhoto = customerInfo && customerInfo.customerPhoto ? customerInfo.customerPhoto : oldCustomerInfo.customerPhoto;
      customerInfo.residentialStatus = customerInfo && customerInfo.residentialStatus && customerInfo.residentialStatus !== 'NULL' ? customerInfo.residentialStatus : oldCustomerInfo.residentialStatus;
      customerInfo.customerTypes = customerInfo && customerInfo.customerTypes ? customerInfo.customerTypes : oldCustomerInfo.customerTypes;
      const contacts = result.customerInfo.contacts;
      const gamePref = result.customerInfo.gamePref;
      const terminalInfos = result.customerInfo.terminalInfos;
      const preExpiyDate = result.customerInfo.preExpiyDate;
      const isFavorite = result.customerInfo.isFavorite;
      const drivingLicence = result.customerInfo.drivingLicence; //驾照
      const otherDocuments = result.customerInfo.otherDocuments; //其他类型
      return {
        ...state,
        customerInfo,
        contacts,
        gamePref,
        terminalInfos,
        preExpiyDate,
        isFavorite,
        drivingLicence,
        otherDocuments,
      };
    },
    // 查询客户标签
    labelListlSave(state, { payload: { labelInfo = [], labelActivity = [] } }) {
      return { ...state, labelInfo, labelActivity };
    },
    // //会员卡信息
    // memberListSave(state, { payload:  result} ) {
    //   let memberInfo =result.memberList.memberInfo;
    //   let detailInfos = result.memberList.memberInfo.detailInfos;
    //   return {...state,memberInfo,detailInfos};
    // },
    // 客户联系人列表
    associatesListSave(state, { payload: result }) {
      const associatesList = result.associatesList;
      return { ...state, associatesList };
    },
    //eligibility列表
    eligibilityListSave(state, { payload: eligibilityList }) {
      return { ...state, eligibilityList };
    },
    // 客户偏好信息
    preferenceInfoSave(state, { payload: result }) {
      const preferenceInfos = result && result.preferenceInfos ? result.preferenceInfos : [];
      const preferenceInfo = [{ 'dataMap': {} }];
      // const infoArrays = [];
      preferenceInfos.forEach(item => {
        // const dataMap = {};
        if (item.subType === 'largestTwinGame') {
          preferenceInfo[0].dataMap.largestTwinGame = item.values[0].message;
        } else if (item.subType === 'longestPlayedGame') {
          preferenceInfo[0].dataMap.longestPlayedGame = item.values[0].message;
        } else if (item.subType === 'preferredZone') {
          preferenceInfo[0].dataMap.preferredZone = item.values[0].message;
        }
      });
      // preferenceInfo.push(infoArrays);
      return { ...state, preferenceInfo };
    },
    // vouchers信息
    vouchersSave(state, { payload: result }) {
      const vouchers = result.vouchers;
      return { ...state, vouchers };
    },
    cardDetailSave(state, { payload: result }) {
      return {
        ...state,
        grInfo: result.grInfo,
        inviteInfo: result.inviteInfo,
      };
    },
    transactionLogsSave(state, { transType, resultCode, queryType, payload: result }) {
      if (transType === 1) {
        const all = state.allTransactions;
        const errFlag = resultCode != '0';
        const voucherTrans =
          errFlag || !result ? [] : result.voucherTrans === null ? [] : result.voucherTrans;
        const currentVoucherTrans =
          queryType === 'current' ? voucherTrans : state.currentVoucherTrans;
        const allTransactions =
          queryType === 'current' ? [...state.currentHotelTrans, ...voucherTrans] : all;
        return {
          ...state,
          voucherTrans,
          allTransactions,
          currentVoucherTrans,
          voucherTransErrorFlag: errFlag,
        };
      } else if (transType === 2) {
        const all = state.allTransactions;
        const errFlag = resultCode != '0';
        let hotelTrans = [];
        try {
          hotelTrans =
            errFlag || !result ? [] : result.hotelTrans === null ? [] : result.hotelTrans;
        } catch (e) {
          console.warn(e);
        }
        const current = Number.parseInt(moment().format('YYYYMMDD'));
        const tempHotelTrans = errFlag
          ? []
          : hotelTrans.filter(item => {
            const departure = item.departure
              ? Number.parseInt(item.departure.slice(0, 8))
              : current;
            if (departure >= current) {
              return item;
            }
          });
        const currentHotelTrans = errFlag
          ? []
          : queryType === 'current'
            ? tempHotelTrans
            : state.currentHotelTrans;
        const allTransactions =
          queryType === 'current' ? [...currentHotelTrans, ...state.currentVoucherTrans] : all;
        const localHotelTrans = errFlag ? [] : result.hotelTrans === null ? [] : result.hotelTrans;

        return {
          ...state,
          hotelTransErrorFlag: errFlag,
          hotelTrans: tempHotelTrans,
          localHotelTrans,
          allTransactions,
          currentHotelTrans,
        };
      } else if (transType === 0) {
        const voucherTrans = result.voucherTrans === null ? [] : result.voucherTrans;
        const hotelTrans = result.hotelTrans === null ? [] : result.hotelTrans;
        const current = Number.parseInt(moment().format('YYYYMMDD'));
        const tempHotelTrans = hotelTrans.filter(item => {
          const departure = item.departure ? Number.parseInt(item.departure.slice(0, 8)) : current;
          if (departure >= current) {
            return item;
          }
        });
        const localHotelTrans = result.hotelTrans === null ? [] : result.hotelTrans;
        const allTransactions = [...tempHotelTrans, ...voucherTrans];
        return {
          ...state,
          transactionsStatus: false,
          hasData: true,
          voucherTrans,
          hotelTrans: tempHotelTrans,
          localHotelTrans,
          allTransactions,
        };
      }
    },
    saveCustomerId(state, action) {
      return {
        ...state,
        customerId: action.customerId,
      };
    },
    removeSuccess(state, action) {
      return {
        ...state,
      };
    },
    removeFailure(state, action) {
      //console.log(action.msg);
      return state;
    },
    addSuccess(state, action) {
      return {
        ...state,
      };
    },
    addFailure(state, action) {
      //console.log(action.msg);
      return state;
    },
    hotelLocalSearch(
      state,
      {
        payload: { bookingId, property, startDate, endDate },
      },
    ) {
      let hotelTrans = state.localHotelTrans;
      if (bookingId) {
        hotelTrans = hotelTrans.filter(item => {
          if (item.bookingNumber.toUpperCase().includes(bookingId.toUpperCase())) {
            return item;
          }
        });
      }
      if (property) {
        hotelTrans = hotelTrans.filter(item => {
          if (item.property === property) {
            return item;
          }
        });
      }
      if (startDate && endDate) {
        hotelTrans = hotelTrans.filter(item => {
          const arrival = Number.parseInt(item.arrival.slice(0, 8));
          if (arrival >= Number.parseInt(startDate) && arrival <= Number.parseInt(endDate)) {
            return item;
          }
        });
      }
      // else {
      //   if (!bookingId && !property) {
      //     const current = Number.parseInt(moment().format('YYYYMMDD'));
      //     hotelTrans = hotelTrans.filter(item => {
      //       const departure = Number.parseInt(item.departure.slice(0, 8));
      //       if (departure >= current) {
      //         return item;
      //       }
      //     });
      //   }
      // }
      return {
        ...state,
        hotelTrans,
      };
    },
    StatisticsListlSave(state, { payload: result }) {
      let statisticsDetailList = result.statisticsDetailList;
      return { ...state, statisticsDetailList };
    },
    hotelInfoSave(state, { payload: result }) {
      let hotelInfo = result.hotelInfos;
      return { ...state, hotelInfo };
    },
    passCardSave(state, { payload: result }) {
      let attractionPassInfos = result.attractionPassInfos;
      return { ...state, attractionPassInfos };
    },
    resetErrFlag(state, { payload }) {
      return { ...state, ...payload };
    },
    // 客户实例化属性
    customerAttributeListSave(state, { payload: result }) {
      const customerAttributeList = result.attributeList;
      /* const showIconName = result.attributeList.showIconName;
      const showIcon = result.attributeList.showIcon;*/
      return { ...state, customerAttributeList };
    },
    // 配置属性
    attributeListSave(state, { payload: result }) {
      const attributeList = result.attributeList;
      /* const showIconName = result.attributeList.showIconName;
      const showIcon = result.attributeList.showIcon;*/
      return { ...state, attributeList };
    },
    updateAttributeList(state, { payload }) {
      const bookAttr = payload.bookAttr;
      const { customerAttributeList } = state;
      if (bookAttr) {
        for (let customerAttribute of customerAttributeList) {
          if (customerAttribute.attrCode === bookAttr.attrCode) {
            customerAttribute.editFlag = bookAttr.editFlag;
          }
        }
      }
      return { ...state, customerAttributeList };
    },
    addAttributeList(state, { payload }) {
      const bookAttr = payload.bookAttr;
      const userName = payload.userName;
      const userId = payload.userId;
      const { customerAttributeList } = state;
      let haveCustomerAttribute = false;
      if (bookAttr && customerAttributeList) {
        for (let customerAttribute of customerAttributeList) {
          if (customerAttribute.attrCode === bookAttr.attrCode) {
            haveCustomerAttribute = true;
            let newBookItem = {
              id: new Date().getTime(),
              attrType: customerAttribute.attrType,
              attrSubType: customerAttribute.attrSubType,
              operation: 'A',
              attrCode: customerAttribute.attrCode,
              operator: userName,
              operatorId: userId,
              value: '',
              newDataFlag: true,
              editAble: true,
            };
            customerAttribute.values.unshift(newBookItem);
            break;
          }
        }
      }
      if (!customerAttributeList || customerAttributeList.length === 0 || !haveCustomerAttribute) {
        let newCustomerAttribute = {
          id: new Date().getTime(),
          attrType: bookAttr.attrType,
          attrSubType: bookAttr.attrSubType,
          operation: 'A',
          attrCode: bookAttr.attrCode,
          operator: userName,
          operatorId: userId,
          value: '',
          newDataFlag: true,
          editAble: true,
          values: [],
          attrName: bookAttr.attrName,
          attrSubTypeName: bookAttr.attrSubTypeName,
          attrTypeName: bookAttr.attrTypeName,
          showIconName: bookAttr.showIconName,
          visible: '0',
        };
        let newBookItem = {
          id: new Date().getTime(),
          attrType: bookAttr.attrType,
          attrSubType: bookAttr.attrSubType,
          operation: 'A',
          attrCode: bookAttr.attrCode,
          operator: userName,
          operatorId: userId,
          value: '',
          newDataFlag: true,
          editAble: true,
        };
        newCustomerAttribute.values.unshift(newBookItem);
        customerAttributeList.push(newCustomerAttribute);
      }
      return { ...state, customerAttributeList };
    },
    deleteAttributeList(state, { payload }) {
      const bookAttr = payload.bookAttr;
      const bookItem = payload.bookItem;
      const { customerAttributeList } = state;
      if (bookAttr && bookItem) {
        for (let customerAttribute of customerAttributeList) {
          if (customerAttribute.attrCode === bookAttr.attrCode) {
            let index = -1;
            for (let i = 0; i < customerAttribute.values.length; i++) {
              if (customerAttribute.values[i].id === bookItem.id) {
                index = i;
                break;
              }
            }
            if (index > -1) {
              customerAttribute.values.splice(index, 1);
            }
            break;
          }
        }
      }
      return { ...state, customerAttributeList };
    },
    // 删除othercasino
    deleteOtherCasinoList(state, { payload }) {
      const attr = payload.attr;
      let { customerOtherCasinoList } = state;
      if (attr) {
        let index = -1;
        for (let i = 0; i < customerOtherCasinoList.length; i++) {
          if (customerOtherCasinoList[i].attrCode === attr.attrCode) {
            if (customerOtherCasinoList[i].operation === 'A') {
              index = i;
            } else {
              customerOtherCasinoList[i].operation = 'D';
              if (customerOtherCasinoList[i].level) {
                customerOtherCasinoList[i].level.operation = 'D';
              }
            }
            break;
          }
        }
        if (index > -1) {
          customerOtherCasinoList.splice(index, 1);
        }
      }
      return { ...state, customerOtherCasinoList };
    },

    // 增加otherCasino item
    addOtherCasinoList(state, { payload }) {
      let { customerOtherCasinoList } = state;
      let userName = payload.userName;
      let userId = payload.userId;
      if (!customerOtherCasinoList || customerOtherCasinoList.length < 0) {
        customerOtherCasinoList = [];
      }
      let casino = {
        casinoId: null,
        configId: null,
        attrType: '1011001',
        attrTypeName: 'Other Casino',
        attrCode: '',
        attrName: null,
        attrValue: null,
        inputType: '1',
        visible: '0',
        operator: userName,
        operatorId: userId,
        createTime: null,
        operation: 'A',
        modifyTime: null,
        level: null,
        editFlag: true,
      };
      customerOtherCasinoList.unshift(casino);
      return { ...state, customerOtherCasinoList };
    },

    // casinoLevel键入
    casinoLevelChange(state, { payload }) {
      let attr = payload.attr;
      let value = payload.value;
      let { customerOtherCasinoList } = state;
      for (let casino of customerOtherCasinoList) {
        if (casino.attrCode === attr.attrCode) {
          casino.level.attrValue = value;
          break;
        }
      }
      return { ...state, customerOtherCasinoList };
    },

    // casinoLevel 发生改变
    otherCasinoLevelSelectChange(state, { payload }) {
      let userName = payload.userName;
      let userId = payload.userId;
      let attr = payload.attr;
      let attrCode = attr.attrCode;
      let value = payload.value;
      let { customerOtherCasinoList, customerOtherCasinoConfigList } = state;
      for (let casino of customerOtherCasinoList) {
        if (casino.attrCode === attr.attrCode) {
          for (let config of customerOtherCasinoConfigList) {
            if (
              config.subType === attrCode &&
              config.funcList &&
              config.funcList[0].subFuncList &&
              config.funcList[0].subFuncList[0].itemList
            ) {
              let itemList = config.funcList[0].subFuncList[0].itemList;
              for (let item of itemList) {
                if (item.item == value) {
                  if (!casino.level || casino.level.levelId == '') {
                    casino.level = {
                      levelId: null,
                      attrCode: value,
                      attrName: item.itemName,
                      attrValue: item.itemValue,
                      inputType: '1',
                      visible: '0',
                      operator: userName,
                      operatorId: userId,
                      createTime: null,
                      modifyTime: null,
                      operation: 'A',
                    };
                  }
                  casino.level.attrCode = value;
                  casino.level.attrName = item.itemName;
                  casino.level.attrValue = item.itemValue;
                  if (item.itemValue == 'Others: Enter' && item.remarks == 'Others: Enter') {
                    casino.level.attrValue = '';
                    casino.level.inputType = '4';
                  } else {
                    casino.level.inputType = '1';
                  }
                  if (casino.level.operation === 'D' || casino.level.operation === '') {
                    if (!casino.level.levelId || casino.level.levelId === '') {
                      casino.level.operation = 'A';
                    } else {
                      casino.level.operation = 'M';
                    }
                  }
                  return { ...state, customerOtherCasinoList };
                }
              }
            }
          }
        }
      }
      return { ...state, customerOtherCasinoList };
    },

    // casinoName键入
    casinoNameChange(state, { payload }) {
      let attr = payload.attr;
      let value = payload.value;
      let { customerOtherCasinoList } = state;
      for (let casino of customerOtherCasinoList) {
        if (casino.attrCode === attr.attrCode) {
          casino.attrValue = value;
          break;
        }
      }
      return { ...state, customerOtherCasinoList };
    },

    // casinoName 发生改变
    otherCasinoNameChange(state, { payload }) {
      let attr = payload.attr;
      let attrCode = payload.value;
      let { customerOtherCasinoList, customerOtherCasinoConfigList } = state;
      for (let casino of customerOtherCasinoList) {
        if (casino.attrCode === attrCode) {
          return { ...state, customerOtherCasinoList };
        }
      }
      for (let casino of customerOtherCasinoList) {
        if (casino.attrCode === attr.attrCode) {
          for (let config of customerOtherCasinoConfigList) {
            if (config.subType === attrCode) {
              casino.attrCode = attrCode;
              if (config.subTypeName == 'Others: Enter' && config.remarks == 'Others: Enter') {
                casino.attrValue = '';
                casino.attrName = config.subTypeName;
                casino.inputType = '4';
              } else {
                casino.attrValue = config.subTypeName;
                casino.inputType = '1';
              }
              if (casino.level) {
                casino.level.attrCode = '';
                casino.level.attrValue = '';
                casino.level.inputType = '1';
                if (casino.level.levelId) {
                  casino.level.operation = 'D';
                } else {
                  casino.level.operation = '';
                }
              }
              return { ...state, customerOtherCasinoList };
            }
          }
        }
      }
      return { ...state, customerOtherCasinoList };
    },

    // other casino 进入编辑状态
    enterEditState(state, { payload }) {
      const userId = payload.userId;
      let { editFlag, customerOtherCasinoList } = state;
      for (let casino of customerOtherCasinoList) {
        if (casino.operatorId == userId) {
          casino.editFlag = true;
        }
      }
      editFlag = true;
      return { ...state, editFlag, customerOtherCasinoList };
    },
    // other casino 取消编辑状态
    cancelEditState(state, { payload }) {
      let { editFlag, customerOtherCasinoList, customerOtherCasinoConfirmList } = state;
      editFlag = false;
      customerOtherCasinoList = [];
      for (let casino of customerOtherCasinoConfirmList) {
        let data = {
          casinoId: casino.casinoId,
          configId: casino.configId,
          attrType: casino.attrType,
          attrTypeName: casino.attrTypeName,
          attrCode: casino.attrCode,
          oldAttrCode: casino.oldAttrCode,
          attrName: casino.attrName,
          attrValue: casino.attrValue,
          oldAttrValue: casino.attrValue,
          inputType: casino.inputType,
          visible: casino.visible,
          operator: casino.operator,
          operatorId: casino.operatorId,
          createTime: casino.createTime,
          modifyTime: casino.modifyTime,
          editFlag: false,
          operation: 'M',
          level: {},
        };
        casino.editFlag = false;
        casino.operation = 'M';
        if (casino.level) {
          casino.level.operation = 'M';
          data.level.levelId = casino.level.levelId;
          data.level.attrCode = casino.level.attrCode;
          data.level.oldAttrCode = casino.level.oldAttrCode;
          data.level.attrName = casino.level.attrName;
          data.level.attrValue = casino.level.attrValue;
          data.level.oldAttrValue = casino.level.attrValue;
          data.level.inputType = casino.level.inputType;
          data.level.visible = casino.level.visible;
          data.level.operator = casino.level.operator;
          data.level.operatorId = casino.level.operatorId;
          data.level.createTime = casino.level.createTime;
          data.level.modifyTime = casino.level.modifyTime;
          data.level.operation = 'M';
        }
        customerOtherCasinoList.push(data);
      }
      return { ...state, editFlag, customerOtherCasinoList };
    },
    changeAttributeList(state, { payload }) {
      const bookAttr = payload.bookAttr;
      const bookItem = payload.bookItem;
      const bookItemValue = payload.bookItemValue;
      const { customerAttributeList } = state;
      if (bookAttr && bookItem) {
        for (let customerAttribute of customerAttributeList) {
          if (customerAttribute.attrCode === bookAttr.attrCode) {
            for (let oneObj of customerAttribute.values) {
              if (oneObj.id == bookItem.id) {
                oneObj.value = bookItemValue;
              }
            }
            break;
          }
        }
      }
      return { ...state, customerAttributeList };
    },

    // 客户otherCasino实例化数据
    customerOtherCasinoInfoSave(state, { payload: result }) {
      let customerOtherCasinoList = result.otherCasinoList;
      let customerOtherCasinoConfirmList = [];
      for (let casino of customerOtherCasinoList) {
        let data = {
          casinoId: casino.casinoId,
          configId: casino.configId,
          attrType: casino.attrType,
          attrTypeName: casino.attrTypeName,
          attrCode: casino.attrCode,
          oldAttrCode: casino.attrCode,
          attrName: casino.attrName,
          attrValue: casino.attrValue,
          oldAttrValue: casino.attrValue,
          inputType: casino.inputType,
          visible: casino.visible,
          operator: casino.operator,
          operatorId: casino.operatorId,
          createTime: casino.createTime,
          modifyTime: casino.modifyTime,
          editFlag: false,
          operation: 'M',
          level: {},
        };
        casino.editFlag = false;
        casino.operation = 'M';
        casino.oldAttrCode = casino.attrCode;
        casino.oldAttrValue = casino.attrValue;
        if (casino.level) {
          casino.level.operation = 'M';
          casino.level.oldAttrCode = casino.level.attrCode;
          casino.level.oldAttrValue = casino.level.attrValue;
          data.level.levelId = casino.level.levelId;
          data.level.attrCode = casino.level.attrCode;
          data.level.oldAttrCode = casino.level.attrCode;
          data.level.attrName = casino.level.attrName;
          data.level.attrValue = casino.level.attrValue;
          data.level.oldAttrValue = casino.level.attrValue;
          data.level.inputType = casino.level.inputType;
          data.level.visible = casino.level.visible;
          data.level.operator = casino.level.operator;
          data.level.operatorId = casino.level.operatorId;
          data.level.createTime = casino.level.createTime;
          data.level.modifyTime = casino.level.modifyTime;
          data.level.operation = 'M';
        }
        customerOtherCasinoConfirmList.push(data);
      }
      const editFlag = false;
      return { ...state, customerOtherCasinoList, customerOtherCasinoConfirmList, editFlag };
    },

    // other casino 配置数据
    customerOtherCasinoConfigInfoSave(state, { payload: result }) {
      let customerOtherCasinoConfigList = [];
      if(result && result.configList && result.configList.length>0){
        customerOtherCasinoConfigList = result.configList[0].subList;
      }
      return { ...state, customerOtherCasinoConfigList };
    },

    userRegionWithRmCodeListSave(state, { payload: result }) {
      const userRegionWithRmCodeList = result.userRegionWithRmCodeList;
      return { ...state, userRegionWithRmCodeList };
    },
    // 客户资料历史轨迹查询
    customerChangeTrackingSave(state, { payload: result }) {
      const historyList = result.historyList;
      const totalSize = result.totalSize;
      return {
        ...state,
        historyList,
        historyTotalSize: totalSize,
      };
    },
    // 客户偏好信息
    customerPreferenceInfoSave(state, { payload: result }) {
      const customerPreferenceInfoList = result.preferenceInfos ? result.preferenceInfos : [];
      return { ...state, customerPreferenceInfoList };
    },
    // 客户偏好信息 变更
    changeCustomerPreference(state, { payload }) {
      const preferenceConfig = payload.preferenceConfig;
      const customerPreferenceValue = payload.customerPreferenceValue;
      const addFlag = payload.addFlag;
      let customerPreferenceInfoList = state.customerPreferenceInfoList;
      // console.log('customerPreferenceValue', customerPreferenceValue);
      let exsitCustomerPreference = false;
      for (let customerPreference of customerPreferenceInfoList) {
        if (customerPreference.type === preferenceConfig.subType) {
          exsitCustomerPreference = true;
          if (!addFlag && customerPreference.values && customerPreference.values.length > 0) {
            for (let customerPreferenceSrcValue of customerPreference.values) {
              if (customerPreferenceSrcValue.id === customerPreferenceValue.id) {
                customerPreferenceSrcValue = customerPreferenceValue;
              }
            }
          } else {
            customerPreference.values = customerPreference.values ? customerPreference.values : [];
            customerPreference.values.unshift(customerPreferenceValue);
          }
          break;
        }
      }
      if (!exsitCustomerPreference) {
        let customerPreference = {
          type: preferenceConfig.subType,
          typeName: preferenceConfig.subTypeName,
          subType: preferenceConfig.subTypeName,
          subTypeName: null,
          system: '999',
          values: [],
        };
        customerPreference.values.push(customerPreferenceValue);
        customerPreferenceInfoList.push(customerPreference);
      }
      // console.log('customerPreferenceInfoList', customerPreferenceInfoList);
      return {
        ...state,
        customerPreferenceInfoList,
        preferenceConfigLoading: new Date().getTime(),
      };
    },
    historyLoadingSave(
      state,
      {
        payload: { loading },
      },
    ) {
      return {
        ...state,
        historyLoading: loading,
      };
    },
    campaignTypeSave(state, { payload }) {
      if (!payload || !payload.attrValueList) {
        return;
      }
      const dictList = payload.attrValueList;
      let campaignTypeList = [];
      let temDict = {
        value: 'All Type',
      };
      campaignTypeList.push(temDict);
      for (let dict of dictList) {
        campaignTypeList.push(dict);
      }
      return { ...state, campaignTypeList };
    },
    resetCustomerData(state, { paypload }) {
      return {
        ...state,
        // 客户明细信息
        customerInfo: {},
        contacts: [],
        gamePref: [],
        terminalInfos: [],
        preExpiyDate: '',
        isFavorite: '',
        // 客户标签
        labelInfo: [],
        // 会员卡信息
        memberInfo: [],
        detailInfos: [],
        // 客户联系人列表
        associatesList: [],
        // 客户偏好信息
        preferenceInfo: [],
        // 客户酒店概要
        hotelBookingSummarize: {},
        // 客户vouchers信息
        vouchers: [],
        // 客户grInfo
        grInfo: {},
        // 客户inviteInfo
        inviteInfo: {},
        // 客户voucherTrans
        voucherTrans: [],
        // 客户hotelTrans
        hotelTrans: [],
        localHotelTrans: [],
        authorities: [],
        //allTransactions
        allTransactions: [],
        currentHotelTrans: [],
        currentVoucherTrans: [],
        resultCode: 0,
        voucherTransErrorFlag: false,
        hotelTransErrorFlag: false,
        //allTransactions加载状态
        transactionsStatus: true,
        //客户统计信息
        statisticsDetailList: [],
        //当前酒店入住信息
        hotelInfo: [],
        //查询景点通行证
        attractionPassInfos: [],
        //客户实例化属性
        attributeList: [],
        customerAttributeList: [],
        historyList: [],
        historyTotalSize: 0,
        /*        showIconName:[],
        showIcon: [],*/
        //客户偏好信息
        customerPreferenceInfoList: [],
        // 客户other casiono 实例化数据
        customerOtherCasinoList: [],
        // other casinno config 数据
        customerOtherCasinoConfigList: [],
        customerOtherCasinoConfirmList: [],
        editFlag: false,
        userAccessList: [],
        hotelLogInfos: [],
        campaignTypeList: [],
        compBalance: '',
        nboInfoList: [],
        taskTabActiveKey:'1',
        activityManualStatusList:[],
        activityManualTypeList:[],
        activityManualSubTypeList:[],
        subTypeList:[],
        manualActivityTotal:0,
        manualActivityCurrent:1,
        manualActivityPageSize: 5,
        manualActivityList:[],
      };
    },
    //hotellog

    setOperaList(state, { payload: result }) {
      let hotelLogInfos = result.hotelLogInfos;
      return { ...state, hotelLogInfos };
    },
    saveUserMessage(state, { payload: data }) {
      return { ...state, logsUserMessage: data };
    },
    setLoading: (state, { payload }) => ({
      ...state,
      loading: payload,
    }),
  },
};
